package org.visionlibrary.image.filters.thresholding;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;
import org.visionlibrary.image.model.FilterTools;


public class TwoPeaksAutoThreshold extends AbstractFilter {
	protected int distance = 6;

	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);

		for (int channel = 0; channel < src.getNumBands(); channel++) {
			int[] histogram = FilterTools.getHistogram(src, channel);

			int firstPeak = 0;
			int secondPeak = firstPeak + distance;
			int highsum = 0;
			for (int l = 0; l < histogram.length - distance; l++) {
				if (histogram[l] + histogram[l + distance] > highsum) {
					highsum = histogram[l] + histogram[l + distance];
					firstPeak = l;
					secondPeak = firstPeak + distance;
				}
			}

			int minhistpixels = histogram[firstPeak];
			int minhist = firstPeak;
			for (int l = firstPeak; l < secondPeak; l++) {
				if (histogram[l] < minhistpixels) {
					minhistpixels = histogram[l];
					minhist = l;
				}
			}

			for (int y = 0; y < src.getHeight(); y++)
				for (int x = 0; x < src.getWidth(); x++) {
					int val = src.getSample(x, y, channel);
					if (val > minhist)
						dest.setSample(x, y, channel, 255);
					else
						dest.setSample(x, y, channel, 0);
				}
		}

		return dest;
	}

	public int getDistance() {
		return distance;
	}

	public void setDistance(int distance) {
		this.distance = distance;
	}
}
